import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from "@angular/forms";
import { NzMessageService } from "ng-zorro-antd";
import { Router, ActivatedRoute } from "@angular/router";
import { FcsService } from "../../service/fcs.service";
import { CommonService } from "../../service/common.service";
import { Function, Trigger, Region } from "../class/instance";
import { Environment } from "environments/environment";
import { debounceTime, distinctUntilChanged, first, map, switchMap } from 'rxjs/operators';
import { Observable, Subscriber } from 'rxjs';
import { NavHeaderService } from "@global/layout/default/nav-header/nav-header.service";

@Component({
  selector: 'app-trigger-create',
  templateUrl: './trigger-create.component.html',
  styleUrls: ['./trigger-create.component.less']
})
export class TriggerCreateComponent implements OnInit {
  @ViewChild('triggerFormComponent', { static: true }) triggerFormComponent;
  @Input() fcsInstance: Function;
  @Input() triggerInstance: Trigger;
  @Input() isDetail = false;
  @Input() currentRegion: Region;
  @Input() groupId = '';
  @Input() triggerType = null;
  @Input() functionId = '';
  @Input() isTriggerList: boolean = false;
  isLoadingApplication = true;
  applicationList = [];
  isLoadingFunction = true;
  functionList;
  functionRuntime = "";
  fcsSearch = '';
  triggerForm: FormGroup;
  //触发器类型，去掉全部类型
  typeList: Array<any> = Environment.application.triggerTypeList.filter(item => item.value !== 'all');
  versionList = [];
  timeList = [
    { label: '分钟', value: 'm' },
    { label: '小时', value: 'h' }
  ];
  staticConfig = '@every 1m';
  triggerRule = 'static';
  errorMsg = '';
  disableFunctionOption: boolean = false; //是否禁用函数选择框
  isCrontab: boolean = false; //触发规则是否是Crontab
  editorOptions = {
    language: "json",
    fontFamily: 'Monaco, Menlo, "Ubuntu Mono", Consolas, source-code-pro, monospace;',
    fontSize: "16",
    theme: 'vs'
  };
  invokeEventTpl = "{\r\n    \"key\": \"value\"\r\n}";
  invokeEvent = "";
  openInvokeEvent: boolean = false;

  ossBucket: string;
  ossBucketList = [];
  isLoadingBucket: boolean = false;
  isLoadingVersion: boolean = false; //是否在加载版本
  ossTrigger: string;
  ossTriggerList = [
    { "label": "ObjectCreated:*", "value": "ObjectCreated:*" },
    { "label": "ObjectCreated:Put", "value": "ObjectCreated:Put" },
    { "label": "ObjectCreated:Copy", "value": "ObjectCreated:Copy" },
    { "label": "ObjectCreated:CompleteMultipartUpload", "value": "ObjectCreated:CompleteMultipartUpload" },
    { "label": "ObjectRemoved:*", "value": "ObjectRemoved:*" },
    { "label": "ObjectRemoved:Delete", "value": "ObjectRemoved:Delete" },
    { "label": "ObjectRemoved:DeleteMarkerCreated", "value": "ObjectRemoved:DeleteMarkerCreated" },
  ];

  isLoadingApigGroup: boolean = false;
  apigGroupList = [];
  apigMethodList = [
    { "label": "GET", "value": "0" },
    { "label": "POST", "value": "1" },
    { "label": "PATCH", "value": "2" },
    { "label": "PUT", "value": "3" },
    { "label": "OPTIONS", "value": "4" },
    { "label": "DELETE", "value": "5" },
    { "label": "HEAD", "value": "6" },
  ];
  apigAuthList = [
    { "label": "无认证", "value": "0" },
    { "label": "IAM认证", "value": "1" },
    { "label": "APP认证", "value": "2" },
  ]
  apigEnvironmentList = [
    { "label": "线上", "value": "1" },
    { "label": "测试", "value": "2" }
  ]
  apigProtocalList = [
    { "label": "HTTP", "value": "0" },
    { "label": "HTTPS", "value": "1" }
  ];

  apigGroupId: string; //api分组
  isRelease = '2';//发布环境
  authenticationMode = '0'; //安全认证
  requestProtocol = '0'; //请求协议
  requestMethod = '0'; //请求方法
  backendTimeout; //后端超时时间
  regionCode: string = 'cn-north-3';
  apigTip: string = '当使用 API 网关触发器时，函数返回体必须为如下json格式:\{"statusCode": 200, "isBase64Encoded": false, "headers": \{\}, "body": ""\}';
  constructor(private fb: FormBuilder,
    private commonService: CommonService,
    private fcsService: FcsService,
    private msgService: NzMessageService,
    private activatedRoute: ActivatedRoute,
    private navHeaderService: NavHeaderService) {
    this.triggerForm = this.fb.group({
      groupId: ['', [Validators.required]],
      functionId: ['', [Validators.required]],
      type: [null, [Validators.required]],
      typeName: [''],
      name: ['', [Validators.required, this.nameValidator], [this.nameDuplicateValidator()]],
      targetName: ['LATEST', [Validators.required]],
      triggerRule: [this.triggerRule, [Validators.required]],
      staticNum: [1, [Validators.required]],
      staticUnit: ['m', [Validators.required]],
      cron: ['', [Validators.required]],
      isEnable: [0, [Validators.required]],
      openInvoke: [false],
      param: [''],

      ossBucket: ['', [Validators.required]],
      ossTrigger: ['', [Validators.required]],
      ossTriggerPre: [''],
      ossTriggerSuf: [''],

      apigGroup: [undefined, [Validators.required]],
      apigEnvironment: ['2', [Validators.required]],
      apigProtocal: ['http', [Validators.required]],
      apigMethod: ['GET', [Validators.required]],
      apigAuth: ['0', [Validators.required]],
      apiTimeout: [undefined, [Validators.required, Validators.pattern('^[1-9][0-9]{0,8}$')]],

      httpAuthType: ["anonymous", [Validators.required]],
    });
  }

  async ngOnInit() {
    this.triggerType = null;
    if (this.triggerInstance) {
      this.triggerType = this.triggerInstance["type"];
    }
    //从配置读取的触发器类型，在这里将全部触发器类型去掉
    this.operateTriggerTypes();
    if (this.fcsInstance && this.fcsInstance.groupId) {
      this.groupId = this.fcsInstance.groupId;
      this.setControlVal('targetName', this.fcsInstance.versionId);
      this.getVersionList(this.fcsInstance.groupId, this.fcsInstance.functionId);
      this.functionRuntime = this.fcsInstance.runtime;
    }
    if (this.isDetail || this.triggerInstance) { //详情和配置中创建触发器要，表单不显示应用和函数
      this.triggerForm.removeControl('groupId');
      this.triggerForm.removeControl('functionId');
    } else {
      this.groupId = await this.getApplicationList();
      this.functionId = await this.getFunctionList(this.groupId);
      this.getVersionList(this.groupId, this.functionId);
    }
    this.triggerInstance && this.configInit();
    this.triggerInstance && this.getVersionList(this.triggerInstance.groupId, this.triggerInstance.funcId);
  }

  operateTriggerTypes() {
    if (this.typeList && this.typeList.length > 0) {
      if (this.typeList.filter(item => item.value === 'all')) {
        let index = this.commonService.getObjectArrayIndex(this.typeList, 'value', 'all');
        if (index !== undefined && index != null) {
          this.typeList.splice(index, 1);
        }
      }
    }
  }

  functionChange(functionId) {
    if (this.groupId == "0" || this.functionId == "0") {
      return;
    }
    this.getVersionList(this.groupId, this.functionId);

    let functionInfo = this.functionList.filter(item => item.id == functionId);
    if (functionInfo.length > 0) {
      this.functionRuntime = functionInfo[0].runtime;
    }

    if (this.functionRuntime == "custom-container" && this.triggerType != "http") {
      this.triggerType = null;
    }
    if (this.functionRuntime != "custom-container" && this.triggerType == "http") {
      this.triggerType = null;
    }
  }

  configInit() {
    this.groupId = this.triggerInstance.groupId;
    this.functionId = this.triggerInstance.funcId;
    this.setControlVal('type', this.triggerInstance.type);
    this.setControlVal('name', this.triggerInstance.name || '--');
    let targetName = this.triggerInstance['targetId'] || (this.versionList.length > 0 ? this.versionList[0]['value'] : '') || '';
    this.setControlVal('targetName', targetName);
    for (let i in this.typeList) {
      if (this.typeList[i].value == this.triggerInstance.type) {
        this.setControlVal('typeName', this.typeList[i].label || '--');
        break;
      }
    }
    if (this.triggerInstance.type === 'timer') {
      this.setControlVal('isEnable', !!this.triggerInstance.isEnable);
      this.setControlVal('param', this.triggerInstance.param);
      if (!this.triggerInstance.param || this.triggerInstance.param === '') {
        this.openInvokeEvent = false;
      } else {
        this.openInvokeEvent = true;
      }

      if (this.triggerInstance && this.triggerInstance.config) {
        this.invokeEvent = this.triggerInstance.param;
        if (!this.triggerInstance.param || this.triggerInstance.param === '') {
          this.openInvokeEvent = false;
        } else {
          this.openInvokeEvent = true;
        }
        let config = this.triggerInstance.config;
        // console.log(config.substring(0, 1));
        if (config.substring(0, 1) == '@') {
          this.triggerRule = 'static';
          this.setControlVal('staticNum', parseInt(config.match(/[0-9]+/)[0]));
          this.setControlVal('staticUnit', config.substring(config.length - 1));
        } else {
          this.triggerRule = 'cron';
          this.setControlVal('triggerRule', 'cron');
          this.setControlVal('cron', config);
        }
      }
    } else if (this.triggerInstance.type === 'oss') {
      this.triggerType = 'oss';
      let firstParse = JSON.parse(this.triggerInstance.config);
      let config;
      if (typeof firstParse === 'string') {
        config = JSON.parse(firstParse);
      } else {
        config = firstParse;
      }
      this.setControlVal('ossTrigger', (config && config['event'] && config.event.length > 3 ? config.event.substr(3, config.event.length - 1) : ''));
      this.setControlVal('ossBucket', (config && config['bucketName'] ? config.bucketName : ''));
      this.setControlVal('ossTriggerPre', (config && config['keyFilterRules'] && config['keyFilterRules']['prefix'] ? config.keyFilterRules.prefix : '--'));
      this.setControlVal('ossTriggerSuf', (config && config['keyFilterRules'] && config['keyFilterRules']['suffix'] ? config.keyFilterRules.suffix : '--'));
    } else if (this.triggerInstance.type === 'apig') {
      this.triggerType = 'apig';
      let firstParse = JSON.parse(this.triggerInstance.config);
      let config;
      if (typeof firstParse === 'string') {
        config = JSON.parse(firstParse);
      } else {
        config = firstParse;
      }
      this.setControlVal('apigGroup', (config && config['groupId'] ? config['groupId'] : ''));
      this.apigGroupId = config && config['groupId'];
      this.getApigGroup();
      this.setControlVal('apigEnvironment', (config && config['isRelease'] ? config['isRelease'] : ''));
      this.isRelease = config && config['isRelease'];
      this.setControlVal('apigAuth', (config && config['authenticationMode'] ? config['authenticationMode'] : ''));
      this.authenticationMode = config && config['authenticationMode'];
      this.setControlVal('apigProtocal', (config && config['requestProtocol'] ? config['requestProtocol'] : ''));
      this.requestProtocol = config && config['requestProtocol'];
      this.setControlVal('apigMethod', (config && config['requestMethod'] ? config['requestMethod'] : ''));
      this.requestMethod = config && config['requestMethod'];
      this.setControlVal('apiTimeout', (config && config['backendTimeout'] ? config['backendTimeout'] : ''));
      this.backendTimeout = config && config['backendTimeout'];
    } else if (this.triggerInstance.type === 'http') {
      this.triggerType = 'http';
      let firstParse = JSON.parse(this.triggerInstance.config);
      let config;
      if (typeof firstParse === 'string') {
        config = JSON.parse(firstParse);
      } else {
        config = firstParse;
      }
      this.setControlVal('httpAuthType', config['authType']);
    }
  }

  getApplicationList(): Promise<any> {
    return new Promise((resolve, reject) => {
      this.fcsService.getGroupList().subscribe(res => {
        this.isLoadingApplication = false;
        this.applicationList = res || [];
        if (!this.groupId || this.groupId === '0') {
          this.applicationList.length > 0 && this.setControlVal('groupId', this.applicationList[0].id);
          if (this.applicationList.length > 0) {
            this.groupId = this.applicationList[0].id;
          }
          resolve(this.groupId);
        }
      }, error => {
        this.errorMsg = error;
        this.isLoadingApplication = false;
        resolve(null);
      })
    })
  }

  getVersionList(groupId, functionId) {
    this.isLoadingVersion = true;
    this.fcsService.getVersionList(groupId, functionId).subscribe(res => {
      let versionsRes = res['data'] || [];
      this.isLoadingVersion = false;
      // 防止获取两次版本，先获取版本，然后再获取别名
      this.versionList = this.versionList.filter(item => item.targetType !== 1);
      let versions = versionsRes;
      versions.forEach(item => {
        this.versionList.push({
          label: `${"版本: " + item.VersionName}`,
          value: `${item.VersionId}`,
          targetType: 1
        });
      })
      //获取别名
      this.fcsService.getAliasList(groupId, functionId).subscribe(res => {
        let aliasRes = res['data'] || [];
        let alias = aliasRes;
        this.versionList = this.versionList.filter(item => item.targetType !== 2);
        alias.forEach(item => {
          this.versionList.push({
            label: `${"别名: " + item.aliasName}`,
            value: `${item.aliasId}`,
            targetType: 2
          })
        })
        if (this.triggerInstance && this.triggerInstance.funcId != functionId || (this.triggerInstance == undefined)) {
          this.setControlVal('targetName', this.versionList[0].value);
        }
        /*        if((this.triggerInstance && this.fcsInstance && !this.triggerForm.get('targetName').value && this.versionList.length > 0) ||(!this.triggerInstance && !this.fcsInstance && this.versionList.length > 0) ){
                  this.setControlVal('targetName', this.versionList[0].value);
                }*/
      });
    }, err => {
      this.isLoadingVersion = false;
    })
  }

  getFunctionList(groupId): Promise<any> {
    return new Promise((resolve, reject) => {
      if (groupId && groupId != '' && groupId != '0') {
        this.isLoadingFunction = true;
        this.fcsService.getFuctionList(groupId, '', '', '').subscribe(res => {
          this.functionList = res.result || [];
          if (this.functionList.length <= 0) {
            this.functionList.push({ "functionId": '', functionName: '没有可用的函数' });
            this.functionList.unshift({ "functionId": '', functionName: '' });
            this.disableFunctionOption = true;
          } else {
            this.disableFunctionOption = false;
          }
          if ((this.isTriggerList && this.functionId === '0') || !this.isTriggerList) {
            this.functionId = this.functionList.length > 0 ? this.functionList[0].functionId : '';
            this.isTriggerList = false;
            resolve(this.functionId)
          }
          this.isLoadingFunction = false;
        }, error => {
          this.errorMsg = error;
          this.isLoadingFunction = false;
          resolve(null)
        })
      }
    })
  }

  staticChange() {
    let staticNum = this.triggerForm.get('staticNum').value.toString();
    let staticUnit = this.triggerForm.get('staticUnit').value;
    this.staticConfig = `@every ${staticNum}${staticUnit}`;
  }
  /**
   * 名称校验
   * @param {FormControl} control 控件实例
   */
  nameValidator(control: FormControl): any {
    let name: string = control.value;
    let pattern = new RegExp('^[a-z][-a-z0-9]{0,18}[a-z0-9]$');
    if (!pattern.test(name)) {
      return { name: true };
    }
    return null;
  }

  nameDuplicateValidator() {
    return (control: FormControl): any => {
      return control.valueChanges.pipe(
        distinctUntilChanged(),
        debounceTime(400),
        switchMap(() => this.isUserNameExist(control.value)),
        map(res => res['exist'] === true ? { duplicated: true } : null),
        first()
      );
    };
  }

  isUserNameExist(name: string): Observable<any> {
    if (name) {
      if (this && this.groupId && this.functionId) {
        return this.fcsService.determineTriggerDuplicate(this.groupId, this.functionId, name);
      }
    }
    return new Observable((observer: Subscriber<any>) => {
      setTimeout(() => {
        observer.next({ exist: false });
      }, 2000);
    });
  }

  /**
   * 为表单控件赋值
   * @param {string} formControlName 控件名称
   * @param {(string | boolean)} val 设置的值
   * @memberof APICreateRestComponent
   */
  setControlVal(formControlName: string, val) {
    this.triggerForm.get(formControlName).patchValue(val);
  }

  /**
   * 获取某个表单的值
   */
  getValidateForm(name: string) {
    return this.triggerForm.get(name);
  }

  getInvalidMessage(name) {
    return this.triggerFormComponent.getInvalidMessage(name);
  }

  triggerRuleChange() {
    if (this.triggerRule === 'cron') {
      this.isCrontab = true;
    } else if (this.triggerRule === 'static') {
      this.isCrontab = false;
    }
  }

  openInvokeEventChange() {
    if (this.openInvokeEvent) {
      if (this.invokeEvent === "") {
        this.invokeEvent = this.invokeEventTpl;
      }
    }
  }

  openInvokeChange() {
    console.log(this.openInvokeEvent)
  }

  changeTrigger() {
    if (this.triggerType == 'oss') {
      this.getOssBuckets()
    } else if (this.triggerType == 'apig') {
      this.getApigGroup();
    }
  }

  getOssBuckets() {
    this.isLoadingBucket = true;
    this.fcsService.getOssBucketList(1, 10000).subscribe(res => {
      if (res && res['data']) {
        let resBuckets = res.data;
        if (this.ossBucketList.length <= 0) {
          resBuckets.forEach(item => {
            this.ossBucketList.push({ label: item.bucketName, value: item.bucketName });
          })
        }
      }
      this.isLoadingBucket = false;
    }, err => {
      this.isLoadingBucket = false;
      this.msgService.error('网络错误');
    })
  }

  getApigGroup() {
    this.isLoadingApigGroup = true;
    this.fcsService.getApigGroupList().subscribe(res => {
      this.isLoadingApigGroup = false;
      this.apigGroupList = res['data'] || [];
    }, err => {
      this.apigGroupList = [];
      this.isLoadingApigGroup = false;
    })
  }
  
  refreshTriggerList(){
    this.isLoadingApigGroup = true;
    this.fcsService.getApigGroupList().subscribe(res => {
      this.isLoadingApigGroup = false;
      this.apigGroupList = res['data'] || [];
    }, err => {
      this.apigGroupList = [];
      this.isLoadingApigGroup = false;
    })
  }


  createApigGroup() {
    let regionCode = this.navHeaderService.getCurrentRegion();
    let apigGroupUrl = Environment.application.productUrl + '/apig/#/openAPI/group?region=' + regionCode;
    window.open(apigGroupUrl, '_blank');
  }

  /**
   * 提交表单
   *
   * @returns {boolean}
   * @memberof GroupCreateComponent
   */
  submitForm(): Promise<boolean> {
    let skipVerify = [];
    if (this.triggerRule == 'static') {
      skipVerify.push(
        "cron"
      );
    } else {
      skipVerify.push(
        "staticNum",
        "staticUnit"
      );
    }
    if (this.triggerType === 'timer') {
      skipVerify.push(
        "ossBucket",
        "ossTrigger",
        "apigGroup",
        "apigEnvironment",
        "apigProtocal",
        "apigMethod",
        "apigAuth",
        "apiTimeout",
        "httpAuthType"
      );
    } else if (this.triggerType === 'oss') {
      skipVerify.push(
        "apigGroup",
        "apigEnvironment",
        "apigProtocal",
        "apigMethod",
        "apigAuth",
        "apiTimeout",
        "httpAuthType"
      );
    } else if (this.triggerType === 'apig') {
      skipVerify.push(
        "ossBucket",
        "ossTrigger",
        "httpAuthType"
      );
    } else if (this.triggerType === 'http') {
      skipVerify.push(
        "ossBucket",
        "ossTrigger",
        "apigGroup",
        "apigEnvironment",
        "apigProtocal",
        "apigMethod",
        "apigAuth",
        "apiTimeout"
      );
    }
    //配置触发器，不校验触发器名称
    if (this.triggerInstance) {
      skipVerify.push(
        "name",
      );
    }

    let group = this.triggerForm as FormGroup;
    for (const i in group.controls) {
      if (i) {
        if (skipVerify.indexOf(i) >= 0) {
          group.controls[i].clearValidators();
          group.controls[i].clearAsyncValidators();
          group.controls[i].updateValueAndValidity();
        } else {
          group.controls[i].markAsDirty();
          group.controls[i].updateValueAndValidity();
        }
      }
    }
    //返回一个promise对象才可以调用then等函数
    return new Promise((resolve, reject) => {
      const interval = setInterval(() => {
        if (!group.pending) {
          clearInterval(interval);
          if (!group.valid) {
            resolve(false);
          } else {
            let params: { [index: string]: any } = {};
            // 设置参数
            if (!this.isDetail) {
              for (let i in this.applicationList) {
                if (this.groupId == this.applicationList[i].id) {
                  params['groupName'] = this.applicationList[i].name;
                  break;
                }
              }
              params['groupId'] = this.groupId;
              params['funcId'] = this.functionId;
              if (this.applicationList.filter(item => item.id === this.groupId)[0]) {
                params['groupDisplayName'] = this.applicationList.filter(item => item.id === this.groupId)[0].displayName;
              } else {
                params['groupDisplayName'] = '';
              }
              if (this.functionList && this.functionList.length > 0) {
                for (let i in this.functionList) {
                  if (this.functionId == this.functionList[i].functionId) {
                    params['funcName'] = this.functionList[i].functionName;
                    params['regionCode'] = this.functionList[i].regionCode;
                    params['regionName'] = this.functionList[i].regionName;
                    break;
                  }
                }
              } else {
                if (this.triggerInstance) {
                  params['regionCode'] = this.triggerInstance.regionCode;
                  params['regionName'] = this.triggerInstance.regionName;
                }
              }
              if (this.triggerInstance) {
                params['groupName'] = this.triggerInstance.groupName; //funcName
                params['funcName'] = this.triggerInstance.funcName;
                params['name'] = this.triggerInstance.name;
                params['type'] = this.triggerInstance.type;
              } else {
                if (this.applicationList.length > 0 && this.applicationList.filter(item => item.id).length > 0) {
                  params['groupName'] = this.applicationList.filter(item => item.id)[0].name; //funcName
                } else {
                  params['groupName'] = '';
                }
                if (this.functionList.length > 0 && this.functionList.filter(item => item.functionId === this.functionId).length > 0) {
                  params['funcName'] = this.functionList.filter(item => item.functionId === this.functionId)[0].functionName;
                }
                params['name'] = this.triggerForm.get('name').value;
                params['type'] = this.triggerForm.get('type').value;
              }
            } else {
              params['groupId'] = (this.triggerInstance && this.triggerInstance.groupId) || this.fcsInstance.groupId;
              params['funcId'] = (this.triggerInstance && this.triggerInstance.funcId) || this.fcsInstance.functionId;
              params['groupDisplayName'] = this.fcsInstance.groupDisplayName;
              params['funcName'] = (this.triggerInstance && this.triggerInstance.funcName) || this.fcsInstance.functionName;
              params['groupName'] = (this.triggerInstance && this.triggerInstance.groupName) || this.fcsInstance.groupName;
              params['regionCode'] = (this.triggerInstance && this.triggerInstance.regionCode) || this.fcsInstance.regionCode;
              params['regionName'] = (this.triggerInstance && this.triggerInstance.regionName) || this.fcsInstance.regionName;
              params['name'] = (this.triggerInstance && this.triggerInstance.name) || this.triggerForm.get('name').value;
              params['type'] = (this.triggerInstance && this.triggerInstance.type) || this.triggerForm.get('type').value;
            }

            if (this.triggerType === 'timer') {
              if (this.triggerRule == 'static') {
                params['config'] = "@every " + this.triggerForm.get('staticNum').value + this.triggerForm.get('staticUnit').value;
              } else {
                params['config'] = this.triggerForm.get('cron').value;
              }
              if (this.openInvokeEvent) {
                params['param'] = this.triggerForm.get('param').value;
              }
              let isEnableValue = this.triggerForm.get('isEnable').value
              params['isEnable'] = isEnableValue ? 1 : 0;
            } else if (this.triggerType === 'oss') {
              let ossParam;
              if (!this.triggerInstance) {
                ossParam = {
                  "bucketName": this.ossBucket,
                  "event": "s3:" + this.ossTrigger,//在选择的事件类型前面加上 "s3:"
                  "keyFilterRules": {
                    "prefix": this.triggerForm.get('ossTriggerPre').value,
                    "suffix": this.triggerForm.get('ossTriggerSuf').value
                  },
                };
                params['config'] = JSON.stringify(ossParam);
              } else {
                ossParam = this.triggerInstance.config;
                params['config'] = ossParam;
              }
              params['isEnable'] = 1;
            } else if (this.triggerType === 'apig') { //支持配置，创建和配置走同样的配置传值
              let apigConfig = {
                groupId: this.apigGroupId,
                isRelease: this.isRelease,
                authenticationMode: this.authenticationMode,
                requestProtocol: this.requestProtocol,
                requestMethod: this.requestMethod,
                backendTimeout: this.backendTimeout
              };
              params['config'] = JSON.stringify(apigConfig);
              params['isEnable'] = 1;
            } else if (this.triggerType === 'http') {
              let httpConfig = {
                authType: this.triggerForm.get("httpAuthType").value,
              };
              params['config'] = JSON.stringify(httpConfig);
              params['isEnable'] = 1;
            }
            let targetId = this.triggerForm.get('targetName').value;
            params['targetType'] = this.versionList.filter(item => item.value === targetId)[0]['targetType'];
            params['targetId'] = targetId;
            params['targetName'] = this.versionList.filter(item => item.value === params['targetId']).length > 0 ? (this.versionList.filter(item => item.value === params['targetId'])[0].label.split(':')[1].trim() || '') : '';
            if (this.triggerInstance && this.triggerInstance.id) {
              // 进行编辑请求
              this.fcsService.updateTrigger(this.groupId, this.functionId, this.triggerInstance.id, params).subscribe(
                data => {
                  if (data && data.name) {
                    resolve(true);
                    this.msgService.success(data['message'] || '触发器配置成功！');
                  } else {
                    resolve(false);
                    this.msgService.error(data['message']);
                  }
                },
                err => {
                  resolve(false);
                }
              );
            } else {
              //进行创建请求
              //从triggerList跳转过来的，fcsInstance为undefined
              this.functionId = this.fcsInstance ? this.fcsInstance.functionId : group.controls.functionId.value;
              params['groupId'] = this.fcsInstance ? this.fcsInstance.groupId : group.controls.groupId.value;
              params['funcId'] = this.fcsInstance ? this.fcsInstance.functionId : group.controls.functionId.value;
              this.fcsService.createTrigger(this.groupId, this.functionId, params).subscribe(
                data => {
                  if (data && data.name) {
                    resolve(true);
                    this.msgService.success(data['message'] || '触发器创建成功！');
                  } else {
                    resolve(false);
                    this.msgService.error(data['message']);
                  }
                },
                err => {
                  resolve(false);
                }
              );
            }
          }
        }
      }, 500);
    });
  }

}
